<?php


namespace App\Http\Controllers\Api\Repositories;


use App\Jobs\AttachIpAddressJob;
use App\Jobs\Circle\UpdateCircleCountJob;
use App\Models\Posts\WxPostsTag;
use App\Models\Circle\WxCircle;
use App\Wen\Utils\CommentUtils;
use App\Wen\Utils\FieldUtils;
use App\Wen\Utils\PostUtils;
use App\Wen\Utils\UserUtils;
use App\Wen\Utils\Utils;
use App\Models\Posts\WxComment;
use App\Models\Posts\WxPost;
use App\Models\WxCommentLike;
use App\Models\WxSyncRelation;
use App\Models\User\WxUser;
use App\Wen\Utils\Settings;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;


class WxCommentRepositores
{

    /**
     * @param $posts_id 文章id
     * @param $comment_id 评论id
     * @param $user_id 评论的用户id
     * @param $comment_content 评论内容
     */
    public static function add($posts_id, $comment_id, $reply_user_id, $user_id, $comment_content, $comment_img_url, $comment_state, $device = '')
    {
        DB::beginTransaction();
        try{
            $posts = WxPost::where('id', $posts_id)->first();
            $user = UserUtils::get_cached_user($user_id);
            $agentUser = WxUser::where('id', $reply_user_id)->first();
            $circle_id = $posts->circle_id;
            $circle_user_id = WxCircle::where('id', $circle_id)->value('user_id');
            global $__MINI_GLOBAL_IP__;
            // 0:审核中，1:审核通过，2:驳回
            if (!_empty_($comment_id)) {
                $CommentModel = new WxComment();
                $CommentModel->posts_id = $posts_id;
                $CommentModel->posts_user_id = $posts['user_id'];
                $CommentModel->user_id = $user_id;
                $CommentModel->user_name = $user['user_name'];
                $CommentModel->user_avatar = $user['user_avatar'];

                if($agentUser){
                    $CommentModel->comment_agent_id = $agentUser['id'];
                    $CommentModel->comment_agent_name = $agentUser['user_name'];
                    $CommentModel->comment_agent_avatar = $agentUser['user_avatar'];
                }

                $CommentModel->comment_id = $comment_id;
                $CommentModel->is_sticky = 0;
                $CommentModel->comment_img_url = $comment_img_url;
                $CommentModel->comment_content = warp2br(_mini_phone(_mini_emoji( _mini_aite_replace($comment_content) )));
                $CommentModel->comment_state = $comment_state;
                if($device){
                    $CommentModel->device = $device;
                }
                if($__MINI_GLOBAL_IP__){
                    $CommentModel->ip = $__MINI_GLOBAL_IP__;
                }
                $r = $CommentModel->save();
                $comment_id = $CommentModel->id;
                if ($comment_state == 1) {
                    $comment_count = WxCommentRepositores::commentCount($posts_id) ?: 0;//评论数量
                    $weight = WxPost::where('id', $posts_id)->value('weight');
                    $weight += ( Utils::getDecayCoefficient($comment_count, 5) * 1000);
                    if($weight > time()){
                        $weight = time();
                    }
                    WxPost::withoutSyncingToSearch(function () use ($posts_id, $weight) {
                        WxPost::where('id', $posts_id)->update(['last_reply_at' => current_time(), 'weight' => timetostr($weight)]);
                    });

                    Redis::sadd('realtime:others:set', json_encode([$reply_user_id, 4, 1]));

                    if($reply_user_id != $user['id']){
                        UserUtils::add_user_notice(3002, $reply_user_id, '你的评论收到了一个回复快去看看吧', '「<a href="/pages/user/user?id='.$user['id'].'">'.$user['user_name'].'</a>」' . '回复了您的评论。', 102, $posts_id);
                    }
                    _mini_aite($user_id, $comment_content, 2, false, $posts_id, $comment_id);
                }
                Cache::forget('post:commentCount:'.$posts_id);

                if($__MINI_GLOBAL_IP__){
                    AttachIpAddressJob::dispatch(3, $comment_id)->delay(2);
                }

                DB::commit();
                //修改部分
               return $comment_id;

            } else {

                $CommentModel = new WxComment();
                $CommentModel->posts_id = $posts_id;
                $CommentModel->posts_user_id = $posts['user_id'];
                $CommentModel->user_id = $user_id;
                $CommentModel->user_name = $user['user_name'];
                $CommentModel->user_avatar = $user['user_avatar'];

                $CommentModel->comment_content = _mini_phone(_mini_emoji( _mini_aite_replace($comment_content) ));
                $CommentModel->comment_img_url = $comment_img_url;
                $CommentModel->is_sticky = 0;
                $CommentModel->comment_state = $comment_state;

                if($device){
                    $CommentModel->device = $device;
                }
                if($__MINI_GLOBAL_IP__){
                    $CommentModel->ip = $__MINI_GLOBAL_IP__;
                }

                $r = $CommentModel->save();
                $comment_id = $CommentModel->id;
                if ($comment_state == 1) {
                    $comment_count = WxCommentRepositores::commentCount($posts_id) ?: 0;//评论数量
                    $weight = WxPost::where('id', $posts_id)->value('weight');
                    $weight += ( Utils::getDecayCoefficient($comment_count, 5) * 1000);
                    if($weight > time()){
                        $weight = time();
                    }
                    WxPost::withoutSyncingToSearch(function () use ($posts_id, $weight) {
                        WxPost::where('id', $posts_id)->update(['last_reply_at' => current_time(), 'weight' => timetostr($weight)]);
                    });
                    if($posts['user_id'] != $user['id']){
                        UserUtils::add_user_notice(2005, $posts['user_id'], '收到了一个评论快去看看吧', '「<a href="/pages/user/user?id='.$user['id'].'">'.$user['user_name'].'</a>」' . '评论了您的笔记。', 102, $posts_id);
                    }
                    _mini_aite($user_id, $comment_content, 2, false, $posts_id, $comment_id);
                }
            }

            Redis::sadd('realtime:others:set', json_encode([$circle_id, 2, 5]));
            Redis::sadd('realtime:others:set', json_encode([$posts['user_id'], 4, 5]));
            $tagsIds = WxPostsTag::where('posts_id', $posts_id)->pluck('tags_id');//话题ID列表
            if($tagsIds){
                foreach ($tagsIds as $tag_id){
                    Redis::sadd('realtime:others:set', json_encode([$tag_id, 5, 5]));
                }
            }
            if($circle_id > 0){
                UpdateCircleCountJob::dispatch($circle_id);
            }
            if($circle_user_id){
                Redis::sadd('realtime:others:set', json_encode([$circle_user_id, 4, 5]));
            }
            Redis::sadd('realtime:post:set', $posts_id);
            Cache::forget('post:commentCount:'.$posts_id);
            if($__MINI_GLOBAL_IP__){
                AttachIpAddressJob::dispatch(3, $comment_id)->delay(2);
            }
            DB::commit();
            //修改部分
            return $comment_id;
        } catch (\Exception $e) {
            DB::rollBack();
            _logger_(__file__, __line__, $e->getLine().' '.$e->getMessage());
            return 0;
        }

    }

    /**
     * @param $posts_id 文章id
     * @param $comment_id 评论id
     * @param $user_id 评论的用户id
     * @param $comment_content 评论内容
     */
    public static function admin_add($domain, $posts_id, $comment_id, $reply_user_id, $user_id, $comment_content, $comment_img_url, $external_id = '', $date = '')
    {
        DB::beginTransaction();
        try{

            if($domain && $external_id){
                $inner_id = WxSyncRelationRepositories::wx_comment_id($domain, $external_id);
                if($inner_id){
                    return true;
                }
            }

            $posts = WxPost::where('id', $posts_id)->first();
            $user = UserUtils::get_cached_user($user_id);

            $agentUser = WxUser::where('id', $reply_user_id)->first();

            if (!_empty_($comment_id)) {
                $CommentModel = new WxComment();
                $CommentModel->posts_id = $posts_id;
                $CommentModel->posts_user_id = $posts['user_id'];
                $CommentModel->user_id = $user_id;
                $CommentModel->user_name = $user['user_name'];
                $CommentModel->user_avatar = $user['user_avatar'];
                $CommentModel->comment_agent_id = $agentUser['id'];
                $CommentModel->comment_agent_name = $agentUser['user_name'];
                $CommentModel->comment_agent_avatar = $agentUser['user_avatar'];
                $CommentModel->comment_id = $comment_id;
                $CommentModel->is_sticky = 0;
                $CommentModel->comment_img_url = $comment_img_url;
                $CommentModel->comment_content = _mini_phone(_mini_emoji( _mini_aite_replace($comment_content) ));
                $CommentModel->comment_state = 1;
                $CommentModel->device = ['app', 'mp'][(int)mini_rand(0,1)];
                if($date){
                    $CommentModel->updated_at =  strtotime($date);
                    $CommentModel->created_at = strtotime($date);
                }
                $CommentModel->save();
                $commentId = $CommentModel->id;

                if($domain && $external_id){
                    $sync = new WxSyncRelation();
                    $sync->domain = $domain;
                    $sync->type = 'comment';
                    $sync->inner_id = $commentId;
                    $sync->external_id = $external_id;
                    $sync->status = 1;
                    $sync->save();
                }

                if($reply_user_id != $user['id']) {
                    UserUtils::add_user_notice(3002, $reply_user_id, '你的评论收到了一个回复快去看看吧', '「<a href="/pages/user/user?id=' . $user['id'] . '">' . $user['user_name'] . '</a>」' . '回复了您的评论。', 102, $posts_id);
                }
                _mini_aite($user_id, $comment_content, 2, false, $posts_id, $comment_id);

            } else {
                $CommentModel = new WxComment();
                $CommentModel->posts_id = $posts_id;
                $CommentModel->posts_user_id = $posts['user_id'];
                $CommentModel->user_id = $user_id;
                $CommentModel->user_name = $user['user_name'];
                $CommentModel->user_avatar = $user['user_avatar'];
                $CommentModel->comment_content = _mini_phone(_mini_emoji( _mini_aite_replace($comment_content) ));
                $CommentModel->comment_img_url = $comment_img_url;
                $CommentModel->is_sticky = 0;
                // 判断是否需要审核评论
                $CommentModel->comment_state = 1;
                if($date){
                    $CommentModel->updated_at =  strtotime($date);
                    $CommentModel->created_at = strtotime($date);
                }
                $CommentModel->save();

                $commentId = $CommentModel->id;

                if($domain && $external_id){
                    $sync = new WxSyncRelation();
                    $sync->domain = $domain;
                    $sync->type = 'comment';
                    $sync->inner_id = $commentId;
                    $sync->external_id = $external_id;
                    $sync->status = 1;
                    $sync->save();
                }

                if($posts['user_id'] != $user['id']) {
                    UserUtils::add_user_notice(2005, $posts['user_id'], '收到了一个评论快去看看吧', '「<a href="/pages/user/user?id=' . $user['id'] . '">' . $user['user_name'] . '</a>」' . '评论了您的笔记。', 102, $posts_id);
                }
                _mini_aite($user_id, $comment_content, 2, false, $posts_id, $comment_id);
            }
            Redis::sadd('realtime:post:set', $posts_id);
            update_user_visit($user_id, 1, $posts_id);
            DB::commit();
            return $commentId;
        } catch (\Exception $e) {
            DB::rollBack();
            _logger_(__file__, __line__, $e->getMessage());
            return 0;
        }

    }

    /**
     * 通过笔记ID获取评论列表
     * @param $posts_id
     * @param $limit
     * @return mixed
     */
    public static function getCommentByPostsId($posts_id, $uid = 0, $limit = 10)
    {
        $data = WxComment::where('comment_state', 1)->where('posts_id', $posts_id)
            ->where('comment_id', null)->orderBy('is_sticky', 'desc')->orderBy('created_at', 'desc')
            ->simplePaginate($limit, FieldUtils::commentInfoColums());

        $post_user_id = WxPost::where('id', $posts_id)->value('user_id');
        $data->map(function ($v, $k) use ($uid, $posts_id, $post_user_id) {
            return CommentUtils::comment_process($k, $v, $posts_id, $post_user_id, $uid,  1, 0);
        });
        $data->append(['format_time', 'ip_address']);
        return $data;
    }
   
    /**
     * 获取评论数量
     */
    public static function commentCount($postId)
    {
        return (int)(Cache::remember('post:commentCount:'.$postId, 36000, function () use ($postId){
            return WxComment::where([['posts_id', '=', $postId], ['comment_state', '=', 1]])->count();
        }));

    }
}
